<?php

declare(strict_types=1);

namespace App\Controller\Admin;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Model\Role as ModelRole;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\AdminMiddleware;
use App\Model\AdminUser;
use App\Model\RoleMenu;
use App\Model\AdminMenu;
use Hyperf\DbConnection\Db;

/**
 * @AutoController(prefix="/admin/role")
 * @Middlewares({
 *     @Middleware(AdminMiddleware::class)
 * })
 */
class Role extends AbstractController
{

    public function info() {
        $this->validate([
            'id' => 'required'
        ]);
        $model = ModelRole::find($this->request->input('id'));
        $model->menus;
        return $this->success($model);
    }

    public function list() {
        $data = $this->request->all();
        $query = ModelRole::query();

        if (!empty($data['name'])) {
            $query = $query->where('name', 'like', '%'.$data['name'].'%');
        }

        $query = $query->orderBy('id', 'desc');
        if (isset($data['page_size']) && $data['page_size'] <= 0) {
            $list = $query->get();
        }else{
            $list = $query->paginate($data['page_size'] ?? 20);
        }
        return $this->success($list);
    }

    public function save() {
        $this->validate([
            'name' => 'required',
            'menu_ids' => 'array'
        ]);

        $data = $this->request->all();

        if (!empty($data['id']) && $data['id'] == 1) {
            return $this->error('不能编辑超级管理员权限');
        }

        $query = AdminUser::query()
            ->where('name', $data['name']);
        if (!empty($data['id'])) {
            $query = $query->where('id', '<>', $data['id']);
        }
        if ($query->count() > 0) {
            return $this->error('用户名已存在');
        }

        $model = ModelRole::upsert($data);

        if (isset($data['menu_ids']) && is_array($data['menu_ids'])) {
            $roleId = $model->id;
            Db::beginTransaction();
            try {
                RoleMenu::query()->where('role_id', $roleId)->delete();
                $menus = AdminMenu::whereIn('id', $data['menu_ids'])->get();
                foreach ($menus as $m) {
                    RoleMenu::create([
                        'menu_id' => $m['id'],
                        'role_id' => $roleId
                    ]);
                }
                Db::commit();
            }catch(\Exception $ex) {
                Db::rollback();
                return null;
            }
        }

        return $this->success($model);
    }

    public function delete() {
        // $id = $this->request->input('id');
        // if (empty($id)) return $this->error('id不能为空');
        $this->validate([
            'id' => 'required'
        ]);
        $id = $this->request->input('id');
        
        $count = AdminUser::query()->where('role_id', $id)->count();
        if ($count > 0) {
            return $this->error('无法删除，角色正在被使用');
        }

        $model = ModelRole::find($id);
        $res = $model->delete();
        return $this->success($res);
    }

    public function menu() {
        $list = AdminMenu::query()->orderBy('sorting', 'desc')->get();
        return $this->success($list);
    }
}
